package com.your.netty.sample.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.your.netty.sample.biz.OperIntegralExecutor;
import com.your.netty.sample.core.Application;
import com.your.netty.sample.core.RequestData;

public class YourServerHandler extends SimpleChannelInboundHandler<Object> {
	private static final Logger logger = Logger.getLogger(YourServerHandler.class);
	// 拼装业务数据对象
	RequestData requestData = new RequestData();

	public YourServerHandler() {
		super();
		logger.debug("********************");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.debug("read0000000000000000000000000000000");
		if (msg instanceof HttpRequest) {
			HttpRequest request = (HttpRequest) msg;

			// 只允许POST请求
			if (request.method().compareTo(HttpMethod.POST) != 0) {
				ChannelUtil.writeResponseMessage(new ResponseMessage(false, "仅支持POST请求"), ctx, request);
				return;
			}
			QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
			Map<String, List<String>> params = queryStringDecoder.parameters();

			requestData.setSys_id(getValueByParamname("sys_id", params));
			requestData.setSalt(getValueByParamname("salt", params));
			requestData.setSign(getValueByParamname("sign", params));
			requestData.setServiceName(getValueByParamname("serviceName", params));

			// IP
			requestData.setRemoteAddr(ChannelUtil.getIpAddress(ctx, request));
		}

		// 获取body内的参数
		if (msg instanceof HttpContent) {
			String data = null;
			HttpContent httpContent = (HttpContent) msg;

			ByteBuf content = httpContent.content();
			if (content.isReadable()) {
				data = content.toString(CharsetUtil.UTF_8);
			}
			requestData.setHttp_body(data);

			Application.cachedThreadPool.execute(new OperIntegralExecutor(ctx, requestData));
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.warn("网络处理异常" + cause.getMessage(), cause);
		ChannelUtil.writeResponseMessage(new ResponseMessage(false, cause.getMessage()), ctx, null);
	}

	/**
	 * 
	 * 根据参数名称获取值。
	 */
	private String getValueByParamname(String paramname, Map<String, List<String>> params) {
		List<String> vals = params.get(paramname);
		if (vals == null) {
			return null;
		}

		for (String val : vals) {
			return val;
		}
		return null;
	}
}
